package yang.java8.concurrent;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;

public class ConcurrentStudy {

	public static void main(String[] args) throws InterruptedException {
		Atomic();
	}
	
	public static AtomicInteger largest = new AtomicInteger();
	
	public static void Atomic() throws InterruptedException {
		int larger = 100;
		// x为当前值，自动传入。里面会CAS
		largest.updateAndGet(x -> Math.max(x, larger));
		System.out.println(largest.get());
		
		// 分区进行加，最后求和时才进行计算
		final LongAdder adder = new LongAdder();
		ExecutorService pool = Executors.newFixedThreadPool(10);
		for (int i = 0; i < 10; i++) {
			pool.submit(() -> {
				while(Math.random() < 0.3) {
					System.out.println("+1");
					adder.increment();
				}
			});
		}
		pool.shutdown();
		pool.awaitTermination(10, TimeUnit.SECONDS);
		long total = adder.sum();
		System.out.println(total);
		
		LongAccumulator acc = new LongAccumulator(Long::sum, 0);
		acc.accumulate(1L);
	}
	
	public static void HashMapStudy() {
		ConcurrentHashMap<String, LongAdder> map = new ConcurrentHashMap<>();
		map.putIfAbsent("key", new LongAdder());
		map.get("key").increment();
	}

}
